/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { Button, message, Space, Popover, Spin, Popconfirm, Typography } from 'antd';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { DetailTableColumnsItem } from '@/components/_pages/ad/utils/type';
import type { Location } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import {
  getMarketSmsDetailList,
  getMarketSmsDetail,
  resendSms,
  updateMarketSmsDetailNote,
} from '@/services/ad/marketingSms/index';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { history, useLocation } from 'umi';
import styles from './index.less';

const { Paragraph } = Typography;
const Index = () => {
  const location = useLocation() as Location;
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [plaintext, setPlaintext] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [record, setRecord] = useState<any>({});
  const [recordItem, setRecordItem] = useState<any>({});
  const [showPopover, setShowPopover] = useState<string>('');
  const [mobile, setMobile] = useState<string>();
  const [visible, setVisible] = useState<boolean>(false);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const queryTable = async (values: any) => {
    const { current: page_num, pageSize: page_size } = values;
    const { code, data, msg } = await getMarketSmsDetailList({
      page_num,
      page_size,
      batch_id: record.id,
    });
    if (code == 0) {
      return {
        data: data.list,
        total: data.total_count,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const handleVisibleChange = (newVisible: boolean, id: string) => {
    if (newVisible) {
      setLoading(true);
      getMarketSmsDetail({ id }).then((res) => {
        setLoading(false);
        const { code, data, msg } = res;
        if (code == 0) {
          setShowPopover(id);
          if (id == showPopover) {
            setVisible(false);
            setMobile('');
          }
          setMobile(data.mobile);
          setPlaintext([...plaintext, id]);
        } else {
          message.error(msg);
        }
      });
    } else {
      setShowPopover('');
      setVisible(false);
    }
  };
  const handleRemark = (recordItem_: any) => {
    setRecordItem(recordItem_);
    setModalVisible(true);
  };
  const handleCloseRemark = () => setModalVisible(false);

  const handleSend = (id: string) => {
    resendSms({ id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        actionRef.current?.reload();
        message.success('操作成功');
      } else {
        message.error(msg);
      }
    });
  };

  const handleRemarkSubmit = async (values: { remark: string }) => {
    updateMarketSmsDetailNote(values).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        setRecordItem({});
        handleCloseRemark();
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };

  const detailColumns: ProColumns<DetailTableColumnsItem>[] = [
    {
      title: '批次号',
      dataIndex: 'batch_number',
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '账号',
      dataIndex: 'mobile',
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '发送状态',
      dataIndex: 'status',
      search: false,
      align: 'center',
      ellipsis: true,
      render: (_, record_) => {
        const { status } = record_;
        return status === 'receive' ? (
          <Paragraph type='success' style={{ margin: 0 }}>
            成功
          </Paragraph>
        ) : status === 'faild' ? (
          <Paragraph type='danger' style={{ margin: 0 }}>
            失败
          </Paragraph>
        ) : status === 'send' ? (
          <a>已发送</a>
        ) : null;
      },
    },
    {
      title: '失败原因',
      dataIndex: 'fail_reason',
      search: false,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      render: (_, record_) => {
        const { id, is_look, fail_reason } = record_;
        return (
          <Space>
            <a
              style={{
                color: `${is_look == '1' || plaintext.includes(id) ? '#73cc73' : '#3597fd'}`,
              }}
            >
              <Popover
                key={id}
                content={mobile}
                trigger='click'
                open={showPopover == id || visible}
                onOpenChange={(newVisible) => handleVisibleChange(newVisible, id)}
              >
                查看明文
              </Popover>
            </a>
            {fail_reason ? (
              <Popconfirm title='确定重新发送吗' onConfirm={handleSend.bind(null, id)}>
                <a>重新发送</a>
              </Popconfirm>
            ) : null}
            <a onClick={handleRemark.bind(null, record_)}>备注</a>
          </Space>
        );
      },
    },
  ];

  const goBackMarketingSms = () => history.goBack();
  useEffect(() => {
    setRecord(location.query);
  }, [location.key]);
  return (
    <DragTable>
      <Spin spinning={loading} size='large'>
        <ProTable
          rowKey='id'
          className={styles.detailTable}
          actionRef={actionRef}
          toolBarRender={false}
          columns={detailColumns}
          request={queryTable}
          search={{
            span: 24,
            optionRender: () => [
              <Space direction='vertical' key='text'>
                <ProFormText label='短信主题：' readonly fieldProps={{ value: record.subject }} />
                <ProFormText label='短信内容：' readonly fieldProps={{ value: record.content }} />
              </Space>,
              <Button type='primary' onClick={goBackMarketingSms} key='option'>
                返回短信列表
              </Button>,
            ],
          }}
          style={{ padding: 24 }}
        />
      </Spin>
      <ModalForm
        title='备注信息'
        visible={modalVisible}
        formRef={formRef}
        width={500}
        modalProps={{
          destroyOnClose: true,
          onCancel: handleCloseRemark,
        }}
        onFinish={handleRemarkSubmit}
        initialValues={recordItem}
      >
        <ProFormTextArea name='note' />
        <ProFormText hidden name='id' />
      </ModalForm>
    </DragTable>
  );
};

export default Index;
